package com.shushan.home;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.bean.OpenVipBean;
import com.shushan.pages.bean.VipBean;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.service.DialRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.shushanbao.wxapi.WXPayEntryActivity;
import com.shushan.util.DateUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;

/**
 * @ClassName: EyeInstrumentActivity
 * @Desciption: 双十一钜惠
 * @author: yichaohua
 * @date: 2018-11-01
 */
public class EyeInstrumentActivity extends NavigationLoseActivity implements View.OnClickListener {

    private static final String TAG = "EyeInstrumentActivity";

    private TextView payText;
    private TextView wxCopyText;
    private TextView daysText;
    private TextView hourMinText;
    private TextView numsText;
    private TextView spendText;

    private BabyApplication babyApplication = BabyApplication.getInstance();
    private IWXAPI api;
    private OpenVipBean openVipBean;
    private ClipboardManager clipboardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.eye_instrument_activity);

        setTitle("双十一钜惠");

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        initView();

        getData();
    }

    private void initView() {
        spendText = findViewById(R.id.eye_instrument_spend_tv);
        daysText = findViewById(R.id.eye_instrument_days_tv);
        daysText.setText(DateUtils.getDays(20181120) + "");
        hourMinText = findViewById(R.id.eye_instrument_hour_min_tv);
        hourMinText.setText(DateUtils.getHourMinutes(20181120));
        numsText = findViewById(R.id.eye_instrument_nums_tv);
        int hours = DateUtils.getHours(20181101,20181120);
        if(hours > 0){
            numsText.setText("已有" + (2000+(hours*50)) + "人购买学习");
        }
        payText = findViewById(R.id.eye_instrument_pay_tv);
        payText.setOnClickListener(this);
        wxCopyText = findViewById(R.id.eye_instrument_copy_tv);
        wxCopyText.setOnClickListener(this);
    }

    private void getData() {
        showWaitDialog();

        int childId = babyApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_OPEN_VIPS);
        urlParse.putValue("child_id",childId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<VipBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(VipBean vipBean) {
                        if(vipBean != null){
                            List<OpenVipBean> openVipBeanList = vipBean.getOpenVipBeanList();
                            openVipBean = openVipBeanList.get(2);
                            spendText.setText(openVipBean.cost_price + "元");
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.eye_instrument_copy_tv:
                if(clipboardManager == null) {
                    clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                }
                ClipData myClip = ClipData.newPlainText("wx_account","shushan0018");
                clipboardManager.setPrimaryClip(myClip);
                showToast("微信号复制成功");
                break;
            case R.id.eye_instrument_pay_tv:
                orderPay();
                break;
            default:
                break;
        }
    }

    private void orderPay() {
        if(api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        if(openVipBean == null){
            showToast("活动信息为空");
            return;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("pay_type","app")
                .putValue("goods_name","限时活动优惠价￥" + openVipBean.cost_price)
                .putValue("vip_time",openVipBean.vip_time);

        if(BuildConfig.DEBUG){
            urlParse.putValue("money","0.01");
        }else {
            urlParse.putValue("money",openVipBean.cost_price);
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if(wxPayBean != null){
                            PayReq req = new PayReq();
                            req.appId			= wxPayBean.appid;
                            req.partnerId		= wxPayBean.partnerid;
                            req.prepayId		= wxPayBean.prepayid;
                            req.nonceStr		= wxPayBean.noncestr;
                            req.timeStamp		= wxPayBean.timestamp + "";
                            req.packageValue	= wxPayBean.packageName;
                            req.sign			= wxPayBean.sign;
                            req.extData			= "app data"; // optional

                            Log.i(TAG,"out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY,wxPayBean.out_trade_no);
                            WXPayEntryActivity.type = 4;

                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                            if(isChildControl){
                                setAllowBack(true);
                                Intent intent = new Intent(EyeInstrumentActivity.this,DialRTAService.class);
                                intent.putExtra("allowPackName",Constants.ALLOW_WECHAT_PACK_NAME);
                                startService(intent);
                            }

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }else {
                            showToast("返回数据为空");
                        }

                        onBackAction();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }
}
